package com.bestcem.xm.ticket.grpc.client;


import cn.hutool.core.lang.ObjectId;
import com.bestcem.xm.common.core.constant.GrpcClientNames;
import com.bestcem.xm.common.grpc.v1.services.*;
import com.bestcem.xm.sms.grpc.v1.services.SmsServiceGrpc;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.client.inject.GrpcClient;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import zhongyan.xm.base.v1.Base;

import javax.annotation.Nonnull;
import java.util.*;

/**
 * 工单调用 common 模块相关rpc接口客户端
 *
 * @author ympan <yuming.pan@idiaoyan.com>
 * @version v1.0
 * @date 2021/8/31 16:27
 */
@Service
@Slf4j
public class TicketCommonGrpcService {

    @GrpcClient(GrpcClientNames.XM)
    private BpEmailServiceGrpc.BpEmailServiceBlockingStub bpEmailServiceBlockingStub;

    @GrpcClient(GrpcClientNames.XM)
    private BpFeiShuServiceGrpc.BpFeiShuServiceBlockingStub bpFeiShuServiceBlockingStub;

    @GrpcClient(GrpcClientNames.XM)
    private BpWechatWorkServiceGrpc.BpWechatWorkServiceBlockingStub bpWechatWorkServiceBlockingStub;

    @GrpcClient(GrpcClientNames.XM)
    private SmsServiceGrpc.SmsServiceBlockingStub smServiceBlockingStub;

    ///**
    // * 发送邮件通知
    // *
    // * @param receiveUsers 收件人邮箱列表
    // * @param ccUsers      抄送人邮箱列表
    // * @param subject      主题
    // * @param content      内容
    // * @param smtpId       发件箱
    // * @author ympan <yuming.pan@idiaoyan.com>
    // * @date 16:31 2021/8/31
    // */
    //public void sendEmailNotice(@Nonnull Collection<String> receiveUsers, @Nullable Collection<String> ccUsers,
    //                            @Nonnull String subject, @Nonnull String content, @Nullable String smtpId) {
    //    SendEmailNoticeRequest.Builder builder = SendEmailNoticeRequest.newBuilder();
    //    builder.addAllReceiveUsers(receiveUsers);
    //    if (!CollectionUtils.isEmpty(ccUsers)) {
    //        builder.addAllCcUsers(ccUsers);
    //    }
    //    builder.setSubject(subject);
    //    builder.setContent(content);
    //    if (!ObjectUtils.isEmpty(smtpId)) {
    //        builder.setSmtpId(smtpId);
    //    }
    //
    //    try {
    //        SendEmailNoticeResponse response = bpEmailServiceBlockingStub.sendEmailNotice(builder.build());
    //        if (Objects.isNull(response) || Base.Code.ERROR.equals(response.getStatus().getCode())) {
    //            log.error("[Ticket] COMMON sendEmailNotice {},{},{},{},{} Error; ErrorMsg: {}", receiveUsers, ccUsers, subject, content, smtpId, response);
    //        }
    //    } catch (Exception e) {
    //        log.error("[Ticket] COMMON sendEmailNotice {},{},{},{},{} Error; ErrorMsg: {}", receiveUsers, ccUsers, subject, content, smtpId, e.getMessage(), e);
    //    }
    //}


    /**
     * 发送飞书通知服务
     *
     * @param tenantKey       租户密钥
     * @param tenantAppId     租户 appid
     * @param tenantAppSecret 租户 应用密钥
     * @param email           邮箱
     * @param content         内容
     * @author ympan <yuming.pan@idiaoyan.com>
     * @date 16:46 2021/8/31
     */
    public void sendFeiShuNotice(@Nonnull String tenantKey, @Nonnull String tenantAppId, @Nonnull String tenantAppSecret,
                                 @Nonnull String email, @Nonnull String content) {
        SendFeiShuNoticeRequest.Builder builder = SendFeiShuNoticeRequest.newBuilder();
        builder.setTenantKey(tenantKey);
        builder.setTenantAppid(tenantAppId);
        builder.setTenantAppsecret(tenantAppSecret);
        builder.setEmail(email);
        builder.setContent(content);

        try {
            SendFeiShuNoticeResponse response =
                    bpFeiShuServiceBlockingStub.sendFeiShuNotice(builder.build());
            if (Objects.isNull(response) || Base.Code.ERROR.equals(response.getStatus().getCode())) {
                log.error("[Ticket] COMMON sendFeiShuNotice {},{},{},{},{} Error; ErrorMsg: {}", tenantKey, tenantAppId, tenantAppSecret, email, content, response);
            }
        } catch (Exception e) {
            log.error("[Ticket] COMMON sendFeiShuNotice {},{},{},{},{} Error;", tenantKey, tenantAppId, tenantAppSecret, email, content, e);
        }
    }


    /**
     * 发短信
     *
     * @param orgId     组织id
     * @param projectId 问卷id
     * @param userName  奖励名称
     * @param content   发送对象 手机号
     * @param phone     短信发送内容
     * @param type      短信任务码
     * @author gy.liu
     * @date 2021/9/2
     */
    /*public void sendSmsNotice(@Nonnull String orgId, String projectId, String userName,
                              @Nonnull String content, String phone, int type) {
        log.error("需要发送短信");
        SendSmsRequest.Builder builder = SendSmsRequest.newBuilder();
        builder.setOrgId(orgId);
        if (StringUtils.isNotEmpty(projectId)) {
            builder.setProjectId(projectId);
        } else {
            builder.setProjectId("");
        }
        if (StringUtils.isNotEmpty(userName)) {
            builder.setName(userName);
        } else {
            builder.setName("");
        }
        builder.setContent(content);
        builder.setPhone(phone);
        builder.setTypeValue(type);

        try {
            SendSmsResponse response = smServiceBlockingStub.sendSms(builder.build());
            if (Objects.isNull(response) || Base.Code.ERROR.equals(response.getStatus().getCode())) {
                log.error("[Ticket] COMMON sendSmsNotice {},{},{},{},{} Error; ErrorMsg: {}", orgId, projectId, userName, phone, content, response);
            }
        } catch (Exception e) {
            log.error("[Ticket] COMMON sendSmsNotice {},{},{},{},{} Error;", orgId, projectId, userName, phone, content, e);
        }
    }*/


    /**
     * 发送企业微信卡片通知
     *
     * @param orgId                  组织id
     * @param receiveUsers           倍市得 UserID 列表最多支持1000个
     * @param receiveParty           部门ID列表，最多支持100个。
     * @param receiveTags            标签ID列表，最多支持100个。
     * @param page                   点击消息卡片后的小程序页面，仅限本小程序内的页面。该字段不填则消息点击后不跳转。
     * @param title                  消息标题，长度限制4-12个汉字（支持id转译）
     * @param description            消息描述，长度限制4-12个汉字（支持id转译）
     * @param contentItem            消息内容键值对，最多允许10个item; key 长度限制 10汉字 | value 长度限制 30汉字
     * @param emphasisFirstItem      是否放大第一个content_item
     * @param enableIdTrans          表示是否开启id转译，0表示否，1表示是，默认0
     * @param enableDuplicateCheck   表示是否开启重复消息检查，0表示否，1表示是，默认0
     * @param duplicateCheckInterval 表示是否重复消息检查的时间间隔，默认1800s，最大不超过4小时
     */
    public void sendWechatWorkNotice(String orgId
            , Collection<String> receiveUsers, Collection<String> receiveParty, Collection<String> receiveTags
            , String page, String title, String description, Map<String, String> contentItem
            , boolean emphasisFirstItem, int enableIdTrans, int enableDuplicateCheck, int duplicateCheckInterval) {
        SendMiniprogramNoticeRequest.Builder builder = SendMiniprogramNoticeRequest.newBuilder();
        if (ObjectId.isValid(orgId)) {
            builder.setOrgId(orgId);
        }
        if (!CollectionUtils.isEmpty(receiveUsers)) {
            builder.addAllTouser(receiveUsers);
        }
        if (!CollectionUtils.isEmpty(receiveParty)) {
            builder.addAllToparty(receiveParty);
        }
        if (!CollectionUtils.isEmpty(receiveTags)) {
            builder.addAllTotag(receiveTags);
        }
        if (!ObjectUtils.isEmpty(page)) {
            builder.setPage(page);
        }
        if (!ObjectUtils.isEmpty(title)) {
            builder.setTitle(title);
        }
        if (!ObjectUtils.isEmpty(description)) {
            builder.setDescription(description);
        }
        if (!CollectionUtils.isEmpty(contentItem)) {
            List<ContentItem> contentItems = new ArrayList<>();
            contentItem.forEach((key, value) -> {
                ContentItem.Builder contentItemBuilder = ContentItem.newBuilder();
                contentItemBuilder.setKey(key);
                contentItemBuilder.setValue(value);
                contentItems.add(contentItemBuilder.buildPartial());
            });
            builder.addAllContentItem(contentItems);
        }
        builder.setEmphasisFirstItem(emphasisFirstItem);
        builder.setEnableIdTrans(enableIdTrans);
        builder.setEnableDuplicateCheck(enableDuplicateCheck);
        builder.setDuplicateCheckInterval(duplicateCheckInterval);

        try {
            SendMiniprogramNoticeResponse response = bpWechatWorkServiceBlockingStub.sendMiniprogramNotice(builder.buildPartial());
            if (Objects.isNull(response) || Base.Code.ERROR.equals(response.getStatus().getCode())) {
                log.error("[Ticket] COMMON sendWechatWorkNotice {};{};{};{};{};{};{};{};{};{};{};{} Error; ErrorMsg: {}",
                        orgId, receiveUsers, receiveParty, receiveTags, page, title, description, contentItem,
                        emphasisFirstItem, enableIdTrans, enableDuplicateCheck, duplicateCheckInterval, response);
            }
        } catch (Exception e) {
            log.error("[Ticket] COMMON sendWechatWorkNotice {};{};{};{};{};{};{};{};{};{};{};{} Error",
                    orgId, receiveUsers, receiveParty, receiveTags, page, title, description, contentItem,
                    emphasisFirstItem, enableIdTrans, enableDuplicateCheck, duplicateCheckInterval, e);
        }
    }
}
    